package com.xmuexp.e09.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.xmuexp.e09.mapper.GoodsMapper;
import com.xmuexp.e09.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import  com.xmuexp.e09.util.*;
import org.springframework.stereotype.Repository;
import com.xmuexp.e09.model.*;
import com.xmuexp.e09.dao.*;
@Repository
public class GoodsDao {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private RedisUtil redisUtil;
    @Value("${e4109.goods.expiretime}")
    private long goodsTimeout;

    public ReturnObject<List<Goods>> findGoods(GoodsPo goodsPo){

        List<Goods> retGoods = null;
        String key = null;
        if (null != goodsPo.getId() ){
            key = "g_"+goodsPo.getId();
            Goods goods = (Goods) redisUtil.get(key);
            if (null != goods){

                retGoods = new ArrayList<>(1);
                retGoods.add(goods);
                return new ReturnObject<>(retGoods);
            }
        }

        List<GoodsPo> goodsPos = goodsMapper.findGoods(goodsPo);

        retGoods = new ArrayList<>(goodsPos.size());
        ProductPo productPo = null;


            productPo = new ProductPo();


        for (GoodsPo goodsItem : goodsPos) {
            Goods item = new Goods(goodsItem);
                productPo.setGoodsId(goodsItem.getId());
                List<ProductPo> productPos = goodsMapper.findProduct(productPo);
                List<Product> productList = new ArrayList<>(productPos.size());
                for (ProductPo productItem : productPos) {
                    Product product = new Product(productItem);
                    productList.add(product);

                item.setProductList(productList);
            }
            retGoods.add(item);
        }

        if (null != goodsPo.getId() ){

            if (retGoods.size() != 0) {
                redisUtil.set(key, retGoods.get(0), goodsTimeout);
            }else{
                redisUtil.set(key, null, goodsTimeout);
            }
        }


        return new ReturnObject<>(retGoods);
    }










}
